/**
 * Eng3.0 的 多组件开发支持工具
 * 
 */
(function(){
//~~~~~~~~~~~~~~~~~~~~~~~~~
var $_ajax=function(o,z){
    var $=new XMLHttpRequest(),t,d,u,a,s,y,f;
        t=o.type||'post'; //默认post
        t=t.toLowerCase(); 
        d=o.dataType||'json'; //默认json
        d=d.toLowerCase();  
        url='?'+(o.url||''); 
        a=o.async===undefined?true:false; //默认 异步 
        s=o.data;
        f=JSON.stringify(s);
        $.open(t,encodeURI(url),a);   //(请求类型, url指令 ,  是否异步 ))
        //$.open(method, url, async, user, password);
        $.setRequestHeader("Content-type","application/"+d+';charset=utf-8');
        // console.log(f);
        $.send(f||'');
        $.onreadystatechange=function(){
            if($.readyState==4){
                var status= $.status;
                if(status==200||status==304){
                    y=$.responseText;
                    if(o.success)
                     o.success( y?(d=='json'?JSON.parse(y):null):y,z);

                }else{
                    if(o.error)
                    o.error(status,z);
                }
            }
     };
};

// ##################################################################################################################### 
  var EngTools=Object.create(null);
  var iframe=document.createElement('iframe');
  var style=iframe.style;
      style.pointerEvents='none';
      style.width='0px';
      style.height='0px';
      style.visibility='hidden';
      style.position='absolute';     
      iframe.setAttribute('sandbox','allow-same-origin');
      document.body.appendChild(iframe);
      iframe.onload=function(){
          var doc=this.contentDocument;
          var d=queue.shift();
              parser(doc,d[0],function(fun){
                   d[1](fun);
                   if(queue.length>0){
                       iframe.src=queue[0][0]; 
                   }else{
                      FLAG=true;
                   }
              });
      };
      iframe.onerror=function(){
              console.error('Component load fail  '+this.src);
          var d=queue.shift();
              d[1](null);
              if(queue.length>0){
                    iframe.src=queue[0][0]; 
              }else{
                    FLAG=true;
              };
      };
      window.addEventListener('error',function(){
             // debugger
      });

var regWrap=/(\r|\n)/g;
var regEl=/el[\s\n]*:[\s\n]*[^,]*,/;
var regD=/data[\s\n]*:/;
var regLine=/\n|\r/;
var regEng=/new\s+Eng\s*\(\s*\{/
var regHtml=/\.(html|htm)$/;
/**
 * 
 * @param {*} str 
 * @param {*} html 
 * @param {*} css 
 * @returns 
 */
var getCode=function(str,html,css){
            str=str.trim();
        var arr=str.split(regLine),i=0,l=arr.length,s='';
            while(i<l){
                s=arr[i];
                if(regEng.test(s))break;
                i++;
            };
           if(i===l)return null;
            /* 
                arr.slice(0,i)  new Eng 之 前的代码部分
                arr.slice(i,l)  new Eng 到 new 结尾部分的代码
            */
        var  line1='',line2='';

            line1='\nexport default function($_config){';
            line2='\n}';

var code=`
${arr.slice(0,i).join('\n')}
\nvar $_HTML=${JSON.stringify(html)}; 
\nvar $_CSS=$_UNDEFIND_$_undefind_$;
${line1}\n
var $_data=$_config&&$_config.$_data;
var $_caller=$_config&&$_config.$_caller;
var $_KRR=$_config&&$_config.$_KRR;
    $_CSS+=($_config&&$_config.$_css||'');
${ arr.slice(i,l).join('\n').replace(regEl,'el:$_HTML,css:$_CSS,$_KRR:$_KRR,').replace(regD,'data:$_data||') }
    return Eng.getAPP();    
${line2} 
` 
        return code.trim();

};

var parser=function(doc,path,callBack){
    var html=doc.body.children[0],u;
        if(html===u||html.tagName==='SCRIPT'){
             console.error('The dom element in the page body is empty !!');
             callBack(false);
            return;
        }; 
    var scripts=doc.getElementsByTagName('script');
    var i=0,l=scripts.length,script,fun,fun2,code='',f=false;
        while(i<l){
          script=scripts[i];
          if(script.src===''){
              f=true;
              break;
          }; 
          i++;
        };
    var styles=doc.getElementsByTagName('style');
    var css='',cssType='';
        l=styles.length;
        
        if(l>0){
             if(l>1){
                console.error('每个组件只允许有1个 style 标签')
                callBack(false);
                return
             };
             css=styles[0].textContent.trim();
             cssType==style[0].type;
        };

        if(!f){
            console.error('script must exist in the page, and there must be an instance of "new Eng(...)"');
            callBack(false);
            return
        };
       
        code=getCode(script.textContent,Eng.getDomStrict(html),css);
        if(code===null){
            console.error('script must exist in the page, and there must be an instance of "new Eng(...)"');
            callBack(false);
            return
        };
        $_ajax({
            type:'post',
            dataType:'json',
            url:'saveCode',
            data:{
                path:path.replace(regHtml,'.js'),
                script:{
                    code:code,
                },
                css:{
                    type:cssType,
                    code:css
                }
            },
            success:function(d){
               if(d){
                   callBack(true)
               };
            },
            error:function(d){
                callBack(false)
                throw d;
            }
        });     
};


var queue=[];
var FLAG=true;   //确定首次加载
/**
 * html 转组件 js  
 * @param {*} path 
 */
EngTools.htmlToJs=function( path ,callBack ){
    if(queue.indexOf(path)<0){
        queue.push([path,callBack]);
        if(FLAG===true){
              FLAG=false;
              iframe.src=queue[0][0];
        };
    };
};

// #####################################################################################################################


window.Eng_DEV_Tools=EngTools;


})();